# -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 16:25:23 2012

@author: nzhao
"""

from traits.api import HasTraits, Instance, Range, Array, Int
from traitsui.api import View, Group, HGroup, Item, RangeEditor, ArrayEditor, InstanceEditor
from enable.api import ComponentEditor

import numpy as np

from phy.spin.MultiSpin import MultiSpin

from gui.cpmg_spin_half_HF import cpmg_spin_half_hf, control_group, auto_update_group

cpmg_group=Group(
                 auto_update_group,
                 control_group,
                 Group(
                       HGroup(
                              Item('sel_spin', label = ' Use spin: '),
                              Item('coord', label = ' coord = ', style='readonly'),
                              Item('fieldPair', style = 'readonly', editor = ArrayEditor(width = 150, format_str = '%8.3f')),
                              ),
                       show_border = True, label = 'hyperfine'
                       ),
                 Item('plot123', editor=ComponentEditor(), show_label=False),
                 label = 'CPMG-Single sin-1/2'
)

class cpmg_spin_half(cpmg_spin_half_hf, HasTraits):
    multi_spin       = Instance( MultiSpin )    

    maxN = Int(1)
    sel_spin         = Range(low=1, high='maxN', editor = RangeEditor(low=1, high_name = 'maxN', mode = 'spinner'))
    coord            = Array(value = np.array([ 0.,  0.,  0.]), editor = ArrayEditor(width = 80, format_str = '%8.3f'))    
    
    def __init__(self,  multi_spin = None, axes = None):
        if multi_spin is not None:
            self.multi_spin = multi_spin
        else:
            self.multi_spin = MultiSpin()
        self.multi_spin.on_trait_change(self.update_maxN, 'spin_num')
        
        super(cpmg_spin_half, self).__init__(axes)

    def update_maxN(self):
        self.maxN = self.multi_spin.spin_num

    def _sel_spin_changed(self):
        spin = self.multi_spin.spin_list[self.sel_spin - 1]
        self.coord = spin.position()
        Ax, Ay, Az = self.multi_spin.hyperfine(spin, self.axes_b) / 2.0 / np.pi
        self.A_vector.x.value, self.A_vector.y.value, self.A_vector.z.value = Ax, Ay, Az
        
        self.update_fields()

    def _axes_b_changed(self):
        spin = self.multi_spin.spin_list[self.sel_spin - 1]
        self.A_vector.x.value, self.A_vector.y.value, self.A_vector.z.value = self.multi_spin.hyperfine(spin, self.axes_b)
        
        self.update_fields()

    cpmg_view = View(
        cpmg_group,
        title     = 'CPMG',
        width     = .8,
        height    = .9,
        resizable = True,
        buttons   = [ 'OK' ],
        kind      = 'live'
    )
     
if __name__ == '__main__':
    cpmg1 = cpmg_spin_half()
    cpmg1.configure_traits()